var Log = {
	
	elem: false,
	write: function(text) {
	/*
		if(!this.elem) this.elem = $('log');
		this.elem.set('html', text);
		*/
	},

	writeDelay: function(text) {
	/*
		if(!this.elem) this.elem = $('log');
		var that = this;
		(function () { 
			that.elem.set('html', text);
		}).delay(1000);
		*/
	}
	
};

Config.drawMainCircle = true;
Config.fps=25;
Config.animationTime=1000;

var Layout = {

	init: function(type) {
		
		var w = jQuery(document).width();
		var headerOffset = jQuery("#header").height(), navcontOffset=jQuery('#navcontainer').height();
	
		var pad = parseInt( jQuery('#content').css('padding-right'));
		var contentOffset = jQuery('#content').height();

		jQuery('#infovis').css({
			/*
			'width' : (contentOffset-20)+'px',
			'height': (contentOffset-20)+'px',
			*/
			//'position':'absolute',
			//'top': (headerOffset+ navcontOffset+10)+ 'px'
			//'left': (w -contentOffset - pad) + 'px'
		});

		jQuery('#log').css({
			'position':'fixed',
			'top': (headerOffset+ navcontOffset+20)+ 'px',
			'left': ( w  - pad-50) + 'px'
		});
/*
		jQuery('#center').css({
			'width': (w -contentOffset - 2*pad + -370)+'px'
		});
*/
//		centerWidthGraphShown= (w -contentOffset - 2*pad + -370)+'px';
//		centerWidthGraphHidden= (w - 2*pad + -370)+'px';

		if(type=="resize"){
			PageController.canvas.resize((contentOffset-20),(contentOffset-20));
		}
	},

	resize: function() {
		this.init("resize");
	}

};


function init() {
	var w = parseInt( jQuery('#infovis').css('width')), h = parseInt( jQuery('#infovis').css('height'));
	//Create a new canvas instance.
	var canvas = new Canvas('mycanvas', {
		'injectInto':'infovis',
		'width': w,
		'height':h,
		'styles': {
			'fillStyle': '#1667DA',
			'strokeStyle': '#A4A4A4'
		},
		'backgroundCanvas': {
			'styles': {
				'fillStyle': '#1667DA',
				'strokeStyle': '#A4A4A4'
			},

			'impl': {
				'init': function() { },
				'plot': function(canvas, ctx) {
					var pi2 = Math.PI*2;
					ctx.beginPath();
					ctx.arc(0, 0,  ((w < h)? w : h) / 2, 0, pi2, true);
					ctx.stroke();
					ctx.closePath();
				}
			}
			
		}
	});
	

	var ht= new Hypertree(canvas,  {
		clickedNodeId: "",
		clickedNodeName: "",
		canvas:canvas,

		onBeforeCompute: function(node) {
			Log.write("centering...");
		},

		preprocessTree: function(json) {
			var ch = json.children;
			var getNode = function(nodeName) {
				for(var i=0; i<ch.length; i++) {
					if(ch[i].name == nodeName) return ch[i];
				}
				return false;
			};
			json.id = this.clickedNodeId;
			Graph.Util.eachAdjacency(ht.graph.getNode(this.clickedNodeId), function(elem) {
				var nodeTo = elem.nodeTo, jsonNode = getNode(nodeTo.name);
				if(jsonNode) jsonNode.id = nodeTo.id;
			});
		},

		requestGraph: function() {
			var that = this, id = this.clickedNodeId;
			Log.write("requesting info...");
			jQuery.getJSON(
				'json/jsonData.jsf', null,
				function(json) {
					Log.write("morphing...");
					that.preprocessTree(json);
					GraphOp.morph(ht, json, {
						'id': id,
						'type': 'fade',
						'duration':1000,
						hideLabels:true,
					
						onComplete: function() {
							Log.write("done");
						},
					
						onAfterCompute: function(){
						//this.onAfterCompute();
						},
						onBeforeCompute: function(){
						//this.onBeforeCompute();
						}
					});
				});
				
		},

		//Add a controller to assign the node's name to the created label.
		onCreateLabel: function(domElement, node) {
			var elem = jQuery(domElement);
			elem.css('opacity', .6)
			.html(node.name)
			.bind('mouseenter', function() { 
				jQuery(this).fadeTo('normal', 1);
			})
			.bind('mouseleave', function() { 
				jQuery(this).fadeTo('normal', .6);
			})
			.bind('click', function() {
				//if(Log.elem.innerHTML == "done")
					ht.move(node.pos.toComplex());
					ajaxWrapper(node.id);
				//ht.onClick(this.id);
			});
		},

		//Take off previous width and height styles and
		//add half of the *actual* label width to the left position
		// That will center your label (do the math man).
		onPlaceLabel: function(domElement, node) {
			domElement.style.display = "none";
			if(node._depth <= 1) {
				domElement.innerHTML = node.name;
				domElement.style.display = "";
				var left = parseInt(domElement.style.left);
				domElement.style.width = '';
				domElement.style.height = '';
				var w = domElement.offsetWidth;
				domElement.style.left = (left - w /2) + 'px';
			}
		},

		onAfterPlotLine: function (adj) {
		/*
			var context = this.canvas.getCtx();
			var canvas = this.canvas;
			var node = adj.nodeFrom, child = adj.nodeTo;

			var pos = node.pos.toComplex();
			var posChild = child.pos.toComplex();
			var ctx = context;
			//ctx.save();
			context.translate(-(pos.x+posChild.x)/2, -(pos.y+posChild.y)/2);
			context.mozDrawText("Sample String");
			//ctx.restore();

			//var ctx = document.getElementById('mycanvas-canvas').getContext('2d');
			//ctx.fillStyle = "Black";
			//ctx.mozDrawText("Simple String");
			//ctx.fillText = "Sample String";


			//draw arrowhead
			canvas.path('stroke', function(context) {
				var r = 10;
				var ctx = context;
				ctx.save();
				ctx.translate(posChild.x,posChild.y);
				var o = parseFloat(posChild.y-pos.y);
				var a = parseFloat(posChild.x -pos.x);

				if(a !=0){
					var rad = Math.atan2(o,a);
					ctx.rotate(rad);
					ctx.moveTo(2,0);
					ctx.lineTo(-10,-4);
					ctx.lineTo(-10,4);

					ctx.lineTo(2,0);
					ctx.fill();
				}

				ctx.restore();

			});

		*/
	
		},

		onAfterCompute: function() {
			Log.write("done");
			var node = GraphUtil.getClosestNodeToOrigin(ht.graph, "pos");
			this.clickedNodeId = node.id;
			this.clickedNodeName = node.name;
			this.requestGraph();
		}
	} );

	PageController.ht = ht;
	PageController.canvas = canvas;
	
}

var PageController = {
	ht: null,
	busy:false,
	canvas:null,

	makeRequestAndPlot: function(name) {
		
		if(this.busy) return;
		this.busy = true;
		var that = this;
		if(this.ht.busy == true) return;
		Animation.timer = clearInterval(Animation.timer);
		this.ht.busy = false;
		name = encodeURIComponent(name);
		var ht = this.ht;
		ht.controller.clickedNodeId = "";
		ht.controller.clickedNodeName = "";
		
		Log.write("wait for it... it might take a while");
		jQuery.getJSON(
			'json/jsonData.jsf', null,
			function(json) {
				GraphPlot.labelsHidden = false;
				GraphPlot.labels = {};
				jQuery('#mycanvas-label').css('display', '');
				//load weighted graph.
				ht.loadTreeFromJSON(json);
				//compute positions
				ht.compute();
				//make first plot
				ht.plot();
				ht.controller.clickedNodeName = name;
				that.busy = false;
				Log.write("done");
			});
	}
};


function init_graph(){
	Layout.init();
	init();
	PageController.makeRequestAndPlot('node0');
};

/*
jQuery(window).resize( function() {
	//TODO problem z "obrecza"
	getHeight();
	Layout.resize();
	PageController.ht.refresh();
	//PageController.ht.controller.onAfterCompute();
});
*/